package com.fub.view;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.view.ViewGroup.LayoutParams;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.fub.R;
import com.fub.positioning.FingerprintService;
import com.fub.positioning.Measurement;
import com.fub.positioning.ReferencePoint;

public class RPListActivity extends Activity {
	private static final int PADDING = 10;
	private String location;
	private FingerprintService fingerprintManager;
	private ProgressDialog progressDialog;
	private Handler handler;
	private ReferencePoint referencePoint;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.fingerprintManager = FingerprintService.getInstance(this);
		Bundle bundle = this.getIntent().getExtras();
		this.location = bundle.getString("location");
		this.handler = new Handler();
		measureSignalStrength();
		setContentView(R.layout.rplist);
	}

	private void measureSignalStrength() {
		showProcessDialog(this.location);
		Thread thread = new Thread() {
			@Override
			public void run() {
				RPListActivity.this.referencePoint = RPListActivity.this.fingerprintManager.getReferencePoint(RPListActivity.this.location);
				Measurement averageMeasurement = RPListActivity.this.fingerprintManager.measureAndReturnAverage(FingerprintService.NUMBER_MEASUREMENTS_FOR_REFERENCEPOINT);
				RPListActivity.this.referencePoint.setMeasurement(averageMeasurement);
			RPListActivity.this.handler.post(RPListActivity.this.hideProcessDialogAndSetListAdapter);
			}
		};
		thread.start();
	}

	private void showProcessDialog(String duration) {
		this.progressDialog = ProgressDialog
				.show(this, "", "Messe Signalstärken für .  " + this.location
						+ ". Bitte  warten...", true);
		this.progressDialog.show();
	}

	private Runnable hideProcessDialogAndSetListAdapter = new Runnable() {
		@Override
		public void run() {
			RPListActivity.this.progressDialog.hide();
			fillTable();
		}
	};

	private void fillTable() {
		TableLayout tl = (TableLayout) findViewById(R.id.rpTable);		
		for (String ssid : this.referencePoint.getMeasurement().getSSids()) {
			
			TableRow row = new TableRow(this);
			TextView ssidTxtView = createTextViews(ssid);
			row.addView(ssidTxtView);		
			TextView levelTxtView = createTextViews(String.valueOf(this.referencePoint.getMeasurement().getSingnalStrength(ssid)));
			row.addView(levelTxtView);
			tl.addView(row, new TableLayout.LayoutParams(
					LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
		}
		tl.invalidate();
	}

	private TextView createTextViews(String text) {
		TextView textView = new TextView(this);
		textView.setText(text);
		textView.setPadding(PADDING, PADDING, PADDING, PADDING);
		return textView;
	}
}
